<template>
  <!-- 搜索栏 -->
  <SearchBar @onSearch="onSearch" />
  <!-- /搜索栏 -->
  <!-- 操作按钮 -->
  <el-row>
    <el-col :span="2">
      <el-button type="primary" @click="$router.push('/itemAdd')">单个新增</el-button>
    </el-col>
    <el-col :span="2">
      <el-upload
        action="#"
        :show-file-list="false"
        name="pic"
        accept=".xlsx,.xls"
        :limit="1"
        :before-upload="multiAddItem"
      >
        <el-button type="warning">批量新增</el-button>
      </el-upload>
    </el-col>
    <el-col :span="2">
      <a href="javascript:;" @click="exportFile">导出excel模板</a>
    </el-col>
  </el-row>
  <!-- /操作按钮 -->
  <el-table height="500" :data="items">
    <el-table-column prop="itemName" label="商品名" />
    <el-table-column prop="itemPrice" label="价格">
      <template #default="{ row }">
        <el-tag>{{ row.itemPrice }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="itemDesc" label="描述">
      <template #default="{ row }">
        <el-tooltip effect="dark" placement="bottom">
          <template #content>
            <div style="width: 500px">
              {{ row.itemDesc }}
            </div>
          </template>
          {{ row.itemDesc.substr(0, 10) + "..." }}
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="itemStatus" label="上下架">
      <template #default="{ row }">
        <el-switch
          v-model="row.itemStatus"
          :active-value="0"
          :inactive-value="1"
          inline-prompt
          active-text="上架"
          inactive-text="下架"
          @change="changeStatus(row.id, row.itemStatus)"
        />
      </template>
    </el-table-column>
    <el-table-column prop="itemSellCount" label="销量">
      <template #default="{ row }">
        <el-tag :color="row.itemSellCount > 500 ? 'red' : 'green'">{{
          row.itemSellCount
        }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="itemImg" label="商品图片">
      <template #default="{ row }">
        <el-image
          style="width: 50px; height: 50px"
          :src="row.itemImg"
          preview-teleported
          :zoom-rate="1.2"
          :preview-src-list="row.itemImgs.map((img) => img.url)"
          fit="cover"
        />
      </template>
    </el-table-column>
    <el-table-column prop="itemCreateTime" label="上架时间" />
    <el-table-column prop="itemUpdateTime" label="修改时间" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button type="primary" @click="itemUpdate(row.id)" size="small"
          >编辑</el-button
        >
        <el-button type="danger" @click="delItem(row.id)" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页组件 -->
  <el-pagination
    v-model:current-page="page"
    v-model:page-size="pageSize"
    layout="prev, pager, next, jumper, sizes"
    :total="total"
  />

  <!-- /分页组件 -->
</template>

<script>
import { getItems, updateItem, delItem } from "@/api/item";
import SearchBar from "@/components/SearchBar.vue";
import { utils, writeFileXLSX, read } from "xlsx";
export default {
  name: "ItemLists",
  data() {
    return {
      total: 0,
      items: [],
      searchParams: {},
      page: 1,
      pageSize: 10,
    };
  },
  watch: {
    // 监听分页变化 重新请求
    page() {
      this.fetchItems();
    },
    pageSize() {
      this.fetchItems();
    },
  },
  methods: {
    delItem(id) {
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示").then(() => {
        delItem(id).then((res) => {
          if (res.data.code === 200) {
            this.$message({
              message: "删除成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.fetchItems();
                this.page = 1;
                this.pageSize = 10;
                this.searchParams = {};
              },
            });
          }
        });
      });
    },
    itemUpdate(id) {
      this.$router.push({
        path: "/itemUpdate",
        query: {
          id,
        },
      });
    },
    multiAddItem(file) {
      // 导入excel 批量新增商品
      // 将文件转换成arrayBuffer
      const fd = new FileReader();
      fd.readAsArrayBuffer(file);
      fd.onload = () => {
        const wb = read(fd.result);
        const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
        const rawData = utils.sheet_to_json(ws); // generate objects
        const data = rawData.map((item) => {
          return {
            itemName: item.商品名,
            itemPrice: item.商品价格,
            itemDesc: item.商品描述,
          };
        });
        console.log(data);
        // 发送请求 请求批量新增商品接口 传入 data数组
      };
      return false;
    },
    exportFile() {
      // 导出 批量新增商品 excel模板
      const data = [
        {
          商品名: "商品名称a",
          商品价格: 10,
          商品描述: "这是商品描述",
        },
      ];
      const ws = utils.json_to_sheet(data);
      /* create workbook and append worksheet */
      const wb = utils.book_new();
      utils.book_append_sheet(wb, ws, "Data");
      /* export to XLSX */
      writeFileXLSX(wb, "商品列表.xlsx");
    },
    onSearch(searchParams) {
      this.searchParams = searchParams;
      this.fetchItems();
    },
    changeStatus(id, itemStatus) {
      console.log(id, itemStatus);
      updateItem({
        id,
        itemStatus,
      }).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.fetchItems();
              this.page = 1;
              this.pageSize = 10;
              this.searchParams = {};
            },
          });
        }
      });
    },
    fetchItems() {
      getItems({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.data.code === 200) {
          this.items = res.data.data.list;
          this.total = res.data.data.total;
        }
      });
    },
  },
  created() {
    this.fetchItems();
  },
  components: {
    SearchBar,
  },
};
</script>

<style lang="scss" scoped></style>
